/**
 * 自动登陆中间件
 * @returns {function(*, *)}
 */

const config = require('../config/config');
const encryptUtil = require('../utils/encryptUtil');
const logger = require('log4js').getLogger();
const user = require('../app/controller/user');


module.exports = () => {
    return async (ctx, next) => {

        if (config.CHECK_REMEMBER && !ctx.session.loginUser && ctx.cookies.get(config.REMEMBER_KEY)) {
            let remember = encryptUtil.decrypt(ctx.cookies.get(config.REMEMBER_KEY), config.REMEMBER_SALT);

            if (remember) {
                try {
                    remember = JSON.parse(remember);

                    let dbUser = await user.loadUser(remember.name, remember.pwd);

                    if (!dbUser || dbUser.disabled) {
                        throw new Error('not found user');
                    }

                    //save login user info to session
                    ctx.session.loginUser = dbUser;

                    logger.info('-- auto login success,username %s ', remember.name);


                } catch (e) {
                    logger.error('------auto login failed --', e);
                }
            }
        }

        await next();
    }
}